<form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
    <input type="hidden" id="video_id">
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Title')}:</label>
        <div class="col-xs-12 col-sm-8">
            <input id="c-title" class="form-control" name="row[title]" type="text" value="">
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Description')}:</label>
        <div class="col-xs-12 col-sm-8">
            <textarea id="c-description" class="form-control editor" rows="5" name="row[description]" cols="50"></textarea>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('madContent')}:</label>
        <div class="col-xs-12 col-sm-8">
            <textarea id="c-mad_content" class="form-control editor" rows="5" name="row[mad_content]" cols="50"></textarea>
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Media_type')}:</label>
        <div class="col-xs-12 col-sm-8">

            <select id="c-media_type" class="form-control selectpicker" name="row[media_type]">
                {foreach name="mediaTypeList" item="vo"}
                <option value="{$key}" {in name="key" value="1" }selected{/in}>{$vo}</option>
                {/foreach}
            </select>

        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('Cover_Video')}:</label>
        <div class="col-xs-12 col-sm-8">
            <input type="file" id="selectFile" style="opacity: 0;visibility: hidden;position: absolute">
            <div class="input-group" style="width: 100%">
                <span><b>文件名：</b></span>
                <span id="uploadFilename" class="uploadFilename"></span>

                <div class="progress progress-striped">
                    <div id="progress-bar-info" class="progress-bar progress-bar-info" role="progressbar"
                         aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"
                         style="width: 0%;">
                        <span class="sr-only">0% 完成</span>
                    </div>
                </div>

                <a id="previewImage" href="#" class="btn btn-primary" style="float: right;">{:__("上传视频/音频")}</a>
            </div>
        </div>
    </div>
</form>

<script src="//libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="/assets/js/backend/lib/es6-promise.min.js"></script>
<script src="/assets/js/backend/lib/aliyun-oss-sdk-5.2.0.min.js"></script>
<script src="/assets/js/backend/aliyun-upload-sdk-1.4.0.min.js"></script>
<script>
    $('#previewImage').on('click', function () {
        $("#selectFile").val("");
        $('#selectFile').click();
    });

    var file;
    $('#selectFile').on('change', function (event) {
        file = event.target.files[0];

        check_var();
    });

    var uploader = new AliyunUpload.Vod({
        // 文件上传失败
        'onUploadFailed': function (uploadInfo, code, message) {
            console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
        },
        // 文件上传完成
        'onUploadSucceed': function (uploadInfo) {
            $('#video_id').val(uploadInfo.videoId);

            var videoId = $('#video_id').val();

            if (!videoId) {
                layer.msg('资源未上传成功');
                return;
            }

            var url = "{:url('v_video/save_video')}";
            var data = {'video_id': videoId};
            ajax_post(url, data, "",finish_upload);
        },
        // 文件上传进度
        'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
            var value = (loadedPercent * 100.00).toFixed(2);
            $("#progress-bar-info").css("width", value + "%").text(value + "%");
        },
        // STS临时账号会过期，过期时触发函数
        'onUploadTokenExpired': function (uploadInfo) {
            console.log("onUploadTokenExpired");
            if (isVodMode()) {
                // 实现时，根据uploadInfo.videoId从新获取UploadAuth
                //实际环境中调用点播的刷新上传凭证接口，获取凭证
                //https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
                //获取上传凭证后，调用setUploadAuthAndAddress
                // uploader.resumeUploadWithAuth(uploadAuth);
            } else if (isSTSMode()) {
                // 实现时，从新获取STS临时账号用于恢复上传
                // uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expireTime);
            }
        },
        onUploadCanceled: function (uploadInfo) {
            console.log("onUploadCanceled:file:" + uploadInfo.file.name);
        },
        // 开始上传
        'onUploadstarted': function (uploadInfo) {
            console.log(uploadInfo);
            if (!uploadInfo.videoId)//这个文件没有上传异常
            {
                //获取上传凭证后，调用setUploadAuthAndAddress
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);
            }
        }
        ,
        'onUploadEnd': function (uploadInfo) {
//            console.log("onUploadEnd: uploaded all the files");
        }
    });


    function finish_upload() {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
        history.go(0);
    }

    //获取播放凭证
    function check_var() {
        var title = $('#c-title').val();
        var intro = $('#c-description').val();

        if (!title) {
            layer.msg('资源名称不能为空');
            return;
        }

        if (!intro) {
            layer.msg('描述不能为空');
            return;
        }

        if (!file && !file.name) {
            layer.msg('上传文件不能为空');
            return;
        }

        var mad_content = $('#c-mad_content').val();

        var media_type = $("#c-media_type").val();
        $('#uploadFilename').html(file.name);
        var url = "{:url('v_video/create_video')}";
        var data = {'title': title, 'desc': intro, 'filename': file.name, 'media_type': media_type,'mad_content':mad_content};
        ajax_post(url, data, '', start_resource);
    }

    var uploadAuth, uploadAddress, videoId;

    function start_resource(res) {
        uploadAuth = res.data.uploadAuth;
        uploadAddress = res.data.uploadAddress;
        videoId = res.data.videoId;

        start();
    }

    function start() {
        var userData = '{"Vod":{"StorageLocation":"","UserData":{"IsShowWaterMark":"false","Priority":"7"}}}';
        uploader.addFile(file, null, null, null, userData);
        uploader.startUpload();
    }

    //ajax请求 结束跳转到指定地址
    function ajax_post(url, data, redirect_url, call_back) {
        $.ajax({
            type: "POST",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: url,
            data: data,
            success: function (res) {
                if (res.code == 1) {
                    //回调
                    if (typeof (call_back) == 'function') {
                        call_back(res);
                        return;
                    }

                    layer.msg(res.msg, {time: 3000});
                    //跳转到指定地址
                    if (redirect_url.length > 0) {
                        window.setTimeout(location_url, 1000, redirect_url);
                    }
                } else {
                    layer.msg(res.msg, {time: 3000});
                }
            },
        });
    }

</script>